﻿// NFakeMail - A fake SMTP Server for software testing.
// 
// Copyright (C) 2010, João Angelo
// 
// This file is part of NFakeMail.
//
// NFakeMail is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// NFakeMail is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with NFakeMail; if not, see <http://www.gnu.org/licenses/>.

namespace NFakeMail
{
    using System;
    using System.Collections.Generic;
    using System.Threading;

    /// <summary>
    /// Provides a communication mechanism between the Python SMTP Server and managed code.
    /// </summary>
    /// <remarks>
    /// Internal use only. This class is public because it's called from IronPython code.
    /// </remarks>
    /// <author> jmangelo </author>
    /// <history>
    /// ______________________________________________________________________________________
    /// History :
    /// 20100816 [+] jmangelo     Initial version
    /// ______________________________________________________________________________________
    /// </history>
    public sealed class FakeMailMessageReceiver
    {
        internal FakeMailMessageReceiver()
        {
        }

        internal event EventHandler<FakeMailMessageReceivedEventArgs> MessageReceived;

        public void ReceiveMessage(FakeMailMessage message)
        {
            this.OnMessageReceived(new FakeMailMessageReceivedEventArgs(message));
        }

        public void ReceiveMessage(
            string clientAddress, 
            int clientPort, 
            string from, 
            IEnumerable<string> to, 
            string msg)
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var message = new FakeMailMessage(clientAddress, clientPort, from, to, msg);

                this.ReceiveMessage(message);
            });
        }

        private void OnMessageReceived(FakeMailMessageReceivedEventArgs e)
        {
            var handler = this.MessageReceived;

            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
}
